<template>
  <div>
    <Card v-if='isbodyList'>
      <div class="p-relative">
        <div @click="reset" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">

          <div class="flex-item search-btn">
            <Button type="primary" @click='create'>添加</Button>
          </div>
          <div class="flex-item">
            <Input v-model="initConfig.searchObj.title" placeholder="请输入标题名称"></Input>
          </div>
          <div class="flex-item search-btn" @click="search">
            <Button type="primary">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border
        :no-data-text="initConfig.loadingText ? initConfig.loadingText : '暂无数据'" border ref="tables" editable
        search-place="top">
        <template slot-scope="{ row, index }" slot="is_home" >
          <i-switch size="large"  v-model="row.is_home?true:false"  @on-change='is_home(row,index)'   true-color="#13ce66" false-color="#ff4949" >
           <span slot="open" >是</span>
            <span slot="close">否</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="estate" >
          <i-switch size="large"  v-model="row.estate?true:false"  @on-change='change(row,index)'   true-color="#13ce66" false-color="#ff4949" >
           <span slot="open" >启用</span>
            <span slot="close" >禁用</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="is_stick" >
          <i-switch size="large"  v-model="row.is_stick?true:false"  @on-change='is_stick(row,index)'   true-color="#13ce66" false-color="#ff4949" >
           <span slot="open" >是</span>
            <span slot="close" >否</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='primary' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>
          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='initConfig.page.current' :total="initConfig.page.total"
        :page-size="initConfig.page.pageSize" show-total show-elevator @on-change="changepage"></Page>
    </Card>
    <!-- 添加修改 -->
    <Card v-else>
      <Tabs type="card">
        <TabPane label="基本信息">
          <BaseInfo class='marginbottom100' :isAdd='isAdd' :property='property' :categoryList='categoryList'
            ref="childRules"></BaseInfo>
        </TabPane>
        <TabPane label="文章详情">
          <ArticleDetail></ArticleDetail>
        </TabPane>
        <TabPane label="优化设置">
          <BetterSetting></BetterSetting>
        </TabPane>
      </Tabs>
    </Card>

    <!-- 底部操作按钮 -->
    <div class="footer-fixed-action" v-show="!isbodyList">
      <div class="flex-start-box">
        <Button type="primary" @click='save("formValidate")'>保存</Button>
        <Button class='marginleft10'>重置</Button>
      </div>
    </div>

    <!-- 添加弹窗 -->

    <!-- 删除弹窗 -->
    <Modal v-model="initConfig.delModal" title="提示">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除数据？
      </p>
      <div slot="footer">
        <Button @click='initConfig.delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'
  import {
    tableOption
  } from '../../../data/article-group/article-list.js'
  // 接口
  import {
    getList,
    add,
    input,
    del,
    open,
    editorSave,
    change
  } from '@/api/article-group/article-list.js'
  import {
    initConfig
  } from '@/config/global.js'
  import Tables from '_c/tables'
  import BaseInfo from './base-info/base-info.vue'
  import ArticleDetail from './article-detail/article-detail.vue'
  import BetterSetting from './better-setting/better-setting.vue'

  export default {
    name: 'tables_page',
    components: {
      Tables,
      BaseInfo,
      ArticleDetail,
      BetterSetting

    },
    created() {
      let _this = this
      this.getList()
      this.initConfig.searchObj = {}

    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        roles: state => state.user.roles,
        vuexArticleBasicObj: state => state.article.vuexArticleBasicObj,
        vuexArticleDetail: state => state.article.vuexArticleDetail,
        vuexArticleSeo: state => state.article.vuexArticleSeo,
        propertyArr: state => state.article.propertyArr

      })
    },
    data() {
      return {
        initConfig: initConfig,
        tableOption: tableOption,
        isbodyList: true,
        isAdd: false,
        delId: '',
        property_value_id: [],
        pid: [],
        id: '',
        estate:'',

        property: [],
        categoryList: [],
        data: {
          list: [{
            name: '测试数据',
            id: 1
          }]
        },
        ruleValidate: {
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          sorter: [{
            required: true,
            pattern: /^[0-9]+$/,
            message: '请输入数字',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      ...mapMutations([
        'setVuxproperty',
        'setVuxPropertyArr',
        'setVuexArticleDetail'

      ]),
      // 列表数据
      getList() {
        let _this = this
        _this.data.list = []
        let params = {
          page: this.initConfig.page.current,
          size: this.initConfig.page.size,
          title: this.initConfig.searchObj.title
        }
        getList(params).then(res => {
          console.log(res.data.data)
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list

            _this.initConfig.page.total = result.total
          } else {
            // _this.$Message.error(res.data.message || res.data.msg)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },





      reset() {
        this.initConfig.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.getList()
      },
      // 点击添加
      create() {
        let _this = this;
        this.isbodyList = false
        this.initConfig.isAdd = true
        this.vuexArticleBasicObj.title = ''
            this.vuexArticleBasicObj.source_tip = ''
            this.vuexArticleBasicObj.source_url = ''
            this.vuexArticleBasicObj.sorter = ''
            this.vuexArticleBasicObj.author = ''
            this.vuexArticleBasicObj.product_property_id = ''
            this.vuexArticleBasicObj.remark = ''
        this.property_value_id = [];

        // this.initConfig.form = {} // 表单重置
        // this.handleReset('form') // 验证重置

        open().then(res => {

          if (res.data.status == 1) {
            let result = res.data.data
            this.property = result.property
            this.categoryList = result.categoryList
            _this.id = result.list.id
            console.log(property)
            console.log(this.categoryList, '7777777777777777')
          } else {
            // _this.$Message.error(res.data.message || res.data.msg)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })

      },
      async save(name) {
        let _this = this


        // let flag = await this.$refs['childRules'].validateForm()// 验证子组件表单


        //      let isSinggleTemplate = false
        //      let isNormsTemplate = false

        // if (!flag) {
        //   this.$Message.error('请填完所有必填项')
        //   return
        // }

        // if (!this.vuexArticleBasicObj.cover_image_file_name) {
        //   this.$Message.error('请选择封面')
        //   return
        // }
        // console.log(this.vuexArticleBasicObj.album_imageArr.length)
        // if (this.vuexArticleBasicObj.album_imageArr.length <= 0) {
        //   this.$Message.error('请选择相册图片')
        //   return
        // }




        if (_this.initConfig.isAdd) {
          // 新增
          // basic
          let basicObj = {
            title: this.vuexArticleBasicObj.title, // 产品名称

            author: this.vuexArticleBasicObj.author,
            source_tip: this.vuexArticleBasicObj.source_tip,
            source_url: this.vuexArticleBasicObj.source_url,
            sorter: this.vuexArticleBasicObj.sorter,
            product_property_id: this.vuexArticleBasicObj.product_property_id,
            remark: this.vuexArticleBasicObj.remark

          }


          this.property_value_id = [];
          this.pid = [];
          this.propertyArr.forEach((item, index) => {
            this.property_value_id.push(item.property_value_id)
            this.pid.push(item.pid)

          })

          // seo
          let expandObj = {
            seo_title: this.vuexArticleSeo.seo_title,
            rejump: this.vuexArticleSeo.rejump,
            view_count: this.vuexArticleSeo.view_count,
            tags: this.vuexArticleSeo.tags,
            seo_keywords: this.vuexArticleSeo.seo_keywords,
            seo_description: this.vuexArticleSeo.seo_description,

          }

          let obj = {
            basic: basicObj, //basic
            seo: expandObj, //seo
            parent_id: this.pid,
            at_image: [this.vuexArticleDetail.at_image_file_name], //图片
            au_image: [this.vuexArticleDetail.au_image_file_name], //封面
            content: this.vuexArticleDetail.content,
            propertys: this.property_value_id



            // album_image: this.prodGroupBasicObj.album_imageArr.length ? this.prodGroupBasicObj.album_imageArr.map(res => { return res.file_name }) : [], // 相册 obj

          }

          // 新增接口
          add(obj).then(res => {
            if (res.data.status == 1) {

              _this.$Message.success('操作成功')
              _this.isbodyList = true
              _this.getList() // 重新刷新数据
              this.vuexArticleBasicObj = [],
                this.propertyArr = [],
                this.vuexArticleSeo = []
                _this.setVuxPropertyArr({});
            } else {
              _this.createModal = false
              // axios响应拦截
            }
          }).catch(function(error) {
            // 异常
            _this.createModal = false
            console.log(error)
          })
        } else {

          // 修改
          let basicObj = {
            title: this.vuexArticleBasicObj.title, // 产品名称

            author: this.vuexArticleBasicObj.author,
            source_tip: this.vuexArticleBasicObj.source_tip,
            source_url: this.vuexArticleBasicObj.source_url,
            sorter: this.vuexArticleBasicObj.sorter,
            product_property_id: this.vuexArticleBasicObj.product_property_id,
            remark: this.vuexArticleBasicObj.remark

          }
          this.property_value_id = [];
          this.pid = [];
          this.propertyArr.forEach((item, index) => {
            this.property_value_id.push(item.property_value_id)
            this.pid.push(item.pid)

          })

          // seo
          let expandObj = {
            seo_title: this.vuexArticleSeo.seo_title,
            rejump: this.vuexArticleSeo.rejump,
            view_count: this.vuexArticleSeo.view_count,
            tags: this.vuexArticleSeo.tags,
            seo_keywords: this.vuexArticleSeo.seo_keywords,
            seo_description: this.vuexArticleSeo.seo_description,

          }

          let obj = {
            // 新增待定

            id: this.id,
            basic: basicObj, //basic
            seo: expandObj, //seo
            parent_id: this.pid,
            at_image: [this.vuexArticleDetail.at_image_file_name], //图片
            au_image: [this.vuexArticleDetail.au_image_file_name], //封面
            content: this.vuexArticleDetail.content,
            propertys: this.property_value_id

          }

          // 修改接口
          editorSave(obj).then(res => {
            if (res.data.status == 1) {
              // let result=res.data.data;
              // _this.data.list=result;
              _this.$Message.success('操作成功')
              _this.isbodyList = true
              _this.getList() // 重新刷新数据
            } else {
              // axios响应拦截
            }
          }).catch(function(error) {
            // 异常
            console.log(error)
          })
        }

      },

      async edit(row) {
        let _this = this
        let obj = JSON.parse(JSON.stringify(row)) // 行数据

        _this.id = obj.id

        this.isbodyList = false
        this.initConfig.isAdd = false

        let params = {
          id: obj.id
        }
        input(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data

            _this.data.list = result.list


            this.vuexArticleBasicObj.title = result.detail.title
            this.vuexArticleBasicObj.source_tip = result.detail.source_tip
            this.vuexArticleBasicObj.source_url = result.detail.source_url
            this.vuexArticleBasicObj.sorter = result.detail.sorter
            this.vuexArticleBasicObj.author = result.detail.author
            this.vuexArticleBasicObj.product_property_id = result.detail.product_property_id
            this.vuexArticleBasicObj.remark = result.detail.remark
            this.property = result.property

            this.vuexArticleBasicObj.propertys = result.detail.propertys
            this.vuexArticleBasicObj.categoryList = result.categoryList
            // this.vuexArticleDetail.content = result.detail.content.content

            let imageArr = result.auImage || []
            let tempImage = [];
            for(var i in imageArr){
               tempImage.push(imageArr[i].path);
            }

            let au_image_file_name = tempImage.join(',');
            let au_image = imageArr.map(res => {
              let endStr = res.src.substring(res.src.lastIndexOf('.') + 1, res.src.length)

              return {
                file_name: res.path,
                url: res.src,

              }
            })

            let atImageArr = result.image || []
            let tempAtImage = [];
            for(var i in atImageArr){
               tempAtImage.push(atImageArr[i].path);
            }
            let at_image_file_name = tempAtImage.join(',');
            let at_image = atImageArr.map(res => {
              let endStr = res.src.substring(res.src.lastIndexOf('.') + 1, res.src.length)

              return {
                file_name: res.path,
                url: res.src,

              }
            })

            let detailObj={
              at_image:at_image,
              au_image:au_image,
              content:result.detail.content.content,
              au_image_file_name:tempImage.join(','),
              at_image_file_name :tempAtImage.join(',')
            }
            this.setVuexArticleDetail(detailObj)
            this.setVuxPropertyArr(result.propertyArr);


            // seo
            this.vuexArticleSeo.view_count = result.seo.view_count
            this.vuexArticleSeo.rejump = result.seo.rejump
            this.vuexArticleSeo.seo_description = result.seo.seo_description
            this.vuexArticleSeo.tags = result.seo.tags
            this.vuexArticleSeo.seo_keywords = result.seo.seo_keywords
            this.vuexArticleSeo.seo_title = result.seo.seo_title


            this.categoryList = result.categoryList
            this.propertys = result.propertys


            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false
            // axios响应拦截
          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
        // console.log(obj)

        // this.initConfig.form = obj // 表单重置

        // 赋值接口返回
        // this.handleReset('form') // 验证重置
      },
      // 删除
      del(row) {
        this.initConfig.delModal = true
        this.initConfig.delId = row.id
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.initConfig.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {
            _this.initConfig.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false
            // axios响应拦截
          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      changepage(e) {
        this.initConfig.page.current = e,
          this.getList()
      },

      change(row,index) {
        console.log(row.estate)

        let _this = this;
        let obj = {
            id:row.id,
            act:'estate',
            value:row.estate==1?0:1
        }
        console.log(obj)
        // 修改状态
        change(obj).then(res => {
          if (res.data.status == 1) {
            _this.$Message.success('操作成功')
            _this.data.list[index].estate = obj.value;
            // _this.getList(); //重新刷新数据
          } else {
            //响应拦截里处理
          }
        }).catch(function(error) {
          //异常
          console.log(error)
        })
      },

      is_home(row,index) {

        let _this = this;
        let obj = {
            id:row.id,
            act:'ishome',
            value:row.is_home==1?0:1
        }
        console.log(obj)
        // 修改状态
        change(obj).then(res => {
          if (res.data.status == 1) {
            _this.$Message.success('操作成功')
            _this.data.list[index].is_home = obj.value;
            // _this.getList(); //重新刷新数据
          } else {
            //响应拦截里处理
          }
        }).catch(function(error) {
          //异常
          console.log(error)
        })
      },
      is_stick(row,index) {

        let _this = this;
        let obj = {
            id:row.id,
            act:'isStick',
            value:row.is_stick==1?0:1
        }
        console.log(obj)
        // 修改状态
        change(obj).then(res => {
          if (res.data.status == 1) {
            _this.$Message.success('操作成功')
            _this.data.list[index].is_stick = obj.value;
            // _this.getList(); //重新刷新数据
          } else {
            //响应拦截里处理
          }
        }).catch(function(error) {
          //异常
          console.log(error)
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields()
      }

    }

  }
</script>

<style lang="scss">
  @import "./index.scss";
</style>
